package com.pxmeta.app.webhook.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pxmeta.common.alarm.SwAlarmDTO;
import com.pxmeta.common.core.domain.AjaxResult;
import com.pxmeta.common.utils.StringUtils;
import com.pxmeta.common.utils.SwAlarmUtil;
import com.pxmeta.feishu.service.FeishuService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/alarm")
@Slf4j
public class SwAlarmController {

    @Autowired
    private FeishuService feishuService;

    @Value("${feishu.appId}")
    private String appId;

    @Value("${feishu.appSecret}")
    private String appSecret;

    private final static String RECEIVE_ID = "oc_f8b32bf58dd3675b614a4396e9552ce2"; //告警通知群id


    @PostMapping("/receive")
    @SneakyThrows
    public void receive(@RequestBody List<SwAlarmDTO> alarmList){
        String content = SwAlarmUtil.getContent(alarmList);
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("msg.json");
        String jsonStr = StringUtils.fileToString(inputStream);
        JSONObject json = JSONObject.parseObject(jsonStr);
        JSONArray elements = json.getJSONArray("elements");
        JSONObject alarm = new JSONObject();
        alarm.put("tag","markdown");
        alarm.put("content",content);
        JSONArray array = new JSONArray();
        array.add(alarm);
        array.addAll(elements);
        json.put("elements",array);
        String card = JSONObject.toJSONString(json);
        String token = feishuService.getTenantAccessToken(appId, appSecret);
        feishuService.sendMsg(RECEIVE_ID,card,"interactive",token);
    }


}
